<!--
author: 何其沆(pooky)
desc: Pool - Account Pool
date: 2021-11-12
-->
<template>
  <div class="account-pool">
    <search @search="handleSearch" @reset="handleReset">
      <div style="display: flex">
        <SearchInput searchText="Client Name">
          <a-input v-model:value="clientName" placeholder="Client Name / Abbreviation / Organization" />
        </SearchInput>
        <SearchInput searchText="URL">
          <a-input v-model:value="url" />
        </SearchInput>
        <SearchInput searchText="Mailbox">
          <a-input v-model:value="mailbox" />
        </SearchInput>
        <SearchInput searchText="Status">
          <a-select
            v-model:value="status"
            show-search
            option-filter-prop="label"
            option-label-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option label="All Client" value="-1">All Client</a-select-option>
            <a-select-option label="Unassigned" value="2">Unassigned</a-select-option>
          </a-select>
        </SearchInput>
      </div>
    </search>
    <e-container style="margin-top: 24px">
      <a-spin :spinning="loading" tip="Loading...">
        <a-table
          :columns="columns"
          :data-source="data"
          class="ant-table-striped"
          :expandIconColumnIndex="9"
          :expanded-row-keys="expandedRowKeys"
          :pagination="false"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'tags'">
              <span v-for="(item, index) in record.tags" :key="index">
                <e-tag :item="item" />
              </span>
            </template>
            <template v-if="column.key === 'fullName'">
              <span>
                <a-tooltip>
                  <template #title> Do not contact this client </template>
                  <e-icon v-if="record.fromMLV" type="tips1" fontSize="14px" style="color: #ffaf17; cursor: help" />
                </a-tooltip>
                {{ record.fullName }}
              </span>
            </template>
          </template>
          <template #expandedRowRender="{ record }">
            <active-expend v-if="record.status === 11 && record.list" :record="record" />
            <expend v-if="record.status !== 11 && record.clientPhaseInfo" :record="record" />
          </template>
          <template #expandIcon="{ expanded, record }">
            <a-space>
              <e-icon
                :type="expanded ? 'Hidden' : 'DropDown'"
                color="#a9b5c9"
                font-size="20px"
                style="cursor: pointer"
                @click="handleRowExpand(expanded, record)"
              />
              <!-- Existing Client 可以申请二次开发-->
              <a-button
                v-if="record.status === 11"
                :disabled="record.fromGrade !== userInfo.userInfo.fromGrade"
                size="small"
                type="primary"
                @click="handleClickRevivalButton(record.id)"
              >
                Revival
              </a-button>
            </a-space>
          </template>
          <template #emptyText>
            <e-empty>
              <template #description>
                <div>Please specify at least one search filter</div>
              </template>
            </e-empty>
          </template>
        </a-table>
      </a-spin>
      <div v-if="total > 0" class="pagination">
        <a-pagination
          v-model:current="current"
          v-model:pageSize="pageSize"
          :total="total"
          show-less-items
          :show-size-changer="false"
          @change="changeSize"
        />
      </div>
    </e-container>
    <revival v-model:show="showSelector" :client-id="clientId" />
  </div>
</template>
<script setup>
import { ref, reactive, computed, onBeforeUnmount, inject } from 'vue'
import { useStore } from 'vuex'
import pageColumns from '@/assets/script/page_columns.js'
import EContainer from '@/components/EContainer.vue'
import EIcon from '@/components/EIcon.vue'
import ETag from '@/components/ETag.vue'
import EEmpty from '@/components/EEmpty.vue'
import Search from '../../components/Search.vue'
import SearchInput from '../../components/SearchInput.vue'
import Expend from './components/expend.vue'
import ActiveExpend from './components/activeExpend.vue'
import Revival from './components/Revival.vue'
import TargetClient from '@/api/targetClient.js'
import { CLIENT_IS_REACHED_LIMIT } from '@/constants/message.js'

const { message } = inject('Feedback')
const store = useStore()
const columns = reactive(pageColumns.accountPool)
const current = ref(1)
const pageSize = ref(10)
const clientName = ref('')
const url = ref('')
const mailbox = ref('')
const status = ref('-1')
const columnDataL = ref()
const columnDataP = ref()
const loading = ref(false)
const expandedRowKeys = ref([])
/**
 * 获取列表数据
 * @returns {Promise<void>}
 */
const getList = async () => {
  loading.value = true
  await store
    .dispatch('setPoolTable', {
      clientName: clientName.value.trim(),
      url: url.value.trim(),
      mailbox: mailbox.value.trim(),
      status: Number(status.value),
      page: {
        pageRows: pageSize.value,
        pageIndex: current.value,
        total: 0
      }
    })
    .finally(() => {
      clearLoading()
    })
}
/**
 * 二次开发申请
 */
const clientId = ref(null)
const showSelector = ref(false)
const userInfo = computed(() => store.state.user)
const handleClickRevivalButton = id => {
  TargetClient.isAllowCreate().then(({ data }) => {
    if (data) {
      clientId.value = id
      showSelector.value = true
    } else {
      message.warning(CLIENT_IS_REACHED_LIMIT)
    }
  })
}
/**
 * 行展开、收起
 * @param expanded
 * @param record
 */
const handleRowExpand = async (expanded, record) => {
  if (expanded) {
    expandedRowKeys.value.splice(
      expandedRowKeys.value.findIndex(key => key === record.key),
      1
    )
  } else {
    store.commit('LAST_PROJECT_INFO', {})
    store.commit('CLIENT_PHASE_INFO', {})
    if (record.status === 11) {
      await store
        .dispatch('setLastProjectInfo', {
          clientID: record.id
        })
        .then(() => {
          columnDataL.value = JSON.parse(JSON.stringify(data.value))
          if (
            (!lastProjectInfo.value.total || lastProjectInfo.value.total === 0) &&
            (!lastProjectInfo.value.list || lastProjectInfo.value.list.length === 0)
          ) {
            columnDataL.value[record.key].list = { total: '', list: [] }
          } else {
            columnDataL.value[record.key].list = lastProjectInfo.value
          }
          store.commit('POOL_TABLE', columnDataL.value)
        })
        .then(() => {
          expandedRowKeys.value.push(record.key)
        })
        .finally(() => {
          clearLoading()
        })
    } else {
      await store
        .dispatch('setClientPhaseInfo', {
          clientID: record.id
        })
        .then(() => {
          columnDataP.value = JSON.parse(JSON.stringify(data.value))
          if (
            !clientPhaseInfo.value ||
            clientPhaseInfo.value.length === 0 ||
            JSON.stringify(clientPhaseInfo.value) === '{}'
          ) {
            columnDataP.value[record.key].clientPhaseInfo = {
              clientShareList: [],
              clientPhareList: [
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' }
              ]
            }
          } else {
            columnDataP.value[record.key].clientPhaseInfo = clientPhaseInfo.value
          }
          store.commit('POOL_TABLE', columnDataP.value)
        })
        .then(() => {
          expandedRowKeys.value.push(record.key)
        })
        .finally(() => {
          clearLoading()
        })
    }
  }
}
/**
 * 切换页码
 * @param cur
 */
const changeSize = cur => {
  current.value = cur
  expandedRowKeys.value = []
  getList()
}
/**
 * 搜索
 */
const handleSearch = () => {
  if (clientName.value === '' && url.value === '' && mailbox.value === '' && status.value === '-1') {
    message.error('Please specify at least one search filter')
    store.commit('POOL_TABLE', [])
    store.commit('TOTAL', 0)
    return
  }
  expandedRowKeys.value = []
  current.value = 1
  getList()
}
/**
 * 重置
 */
const handleReset = () => {
  clientName.value = ''
  url.value = ''
  mailbox.value = ''
  status.value = '-1'
  clearData()
}
/**
 * 表格数据
 * @type {ComputedRef<*>}
 */
const data = computed(() => store.state.pool.poolTable)
/**
 * 总条数
 * @type {ComputedRef<*>}
 */
const total = computed(() => store.state.pool.total)
/**
 * status === 11时展开
 * @type {ComputedRef<{}|*>}
 */
const lastProjectInfo = computed(() => store.state.pool.lastProjectInfo)
/**
 * status !=== 11时展开
 * @type {ComputedRef<{}|*>}
 */
const clientPhaseInfo = computed(() => store.state.pool.clientPhaseInfo)
/**
 * 关闭loading
 */
const clearLoading = () => {
  setTimeout(() => {
    loading.value = false
  }, 30)
}
/**
 * 清空数据
 */
const clearData = () => {
  expandedRowKeys.value = []
  store.commit('POOL_TABLE', [])
  store.commit('LAST_PROJECT_INFO', {})
  store.commit('CLIENT_PHASE_INFO', {})
  store.commit('TOTAL', 0)
}
/**
 * 离开清空
 */
onBeforeUnmount(() => {
  clearData()
})
</script>
<style scoped lang="less">
@import '@/assets/style/reset_table';
@import '@/assets/style/reset_form';
</style>
<route lang="yaml">
name: Client Pool
path: '/pool/client-pool'
meta:
  sort: 0
</route>
